package org.javaboy.demo.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Component
@Aspect
@EnableAspectJAutoProxy
public class TxAspect {

    @Autowired
    PlatformTransactionManager transactionManager;

    /**
     * @annotation(org.javaboy.demo.anno.MyTx) 表示如果方法上有 @MyTx 注解，则这个方法被拦截
     * @within(org.javaboy.demo.anno.MyTx) 这个表示如果类上面有 @MyTx 注解，则类中的所有方法被拦截
     */
    @Pointcut("@annotation(org.javaboy.demo.anno.MyTx)||@within(org.javaboy.demo.anno.MyTx)")
    public void pc1() {

    }

    @Around("pc1()")
    public Object around(ProceedingJoinPoint pjp) {
        Object proceed = null;
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            proceed = pjp.proceed();
            transactionManager.commit(status);
        } catch (Throwable e) {
            transactionManager.rollback(status);
            throw new RuntimeException(e);
        }
        return proceed;
    }
}
